
% INPUT - Line profile raw data 
    % For self-assembled fibrils, use the raw data file 'DataSA'
    % 'DataSA' file contains 30 line profile data 
    
% OUTPUT - Variable 'SA_Dia' which contains the diameter values.
    % The code does a Gaussian fit for each line profile and calculate - 
    % the full width at half maximum (FWHM) for each Gaussian fit. This
    % FWHM value is considered as the diameter for each measurement.

for i=1:length(DataSA.x)

    x = DataSA.x{i}; % x axis data of the 'i' th line profile in nm
    y = DataSA.y{i}; % y axis data of the 'i' th line profile in nm
              


    f1 =createFit(x,y); % call fitting function to fit a Gaussian curve to data
    coef = coeffvalues(f1); % output fitting parameters as coef
    x1 = [min(x):0.1:max(x)];   % create x range to plot the fit
    Yest = gaussian(x1,coef);   % obtain y values form the fit

    % Find the half max value.
    halfMax = (min(Yest) + max(Yest)) / 2;
    % Find where the data first drops below half the max.
    index1 = find(Yest >= halfMax, 1, 'first');
    % Find where the data last rises above half the max.
    index2 = find(Yest >= halfMax, 1, 'last');

    % calculate FWHM
    FWHM = x1(index2) - x1(index1);
    
    figure;
    plot(x,y); % plot raw line profile
    hold on;
    plot(x1,Yest);  %plot Guassian fit

    hold on;
    line([x1(index1), x1(index2)], [Yest(index1), Yest(index2)], 'Color', 'r', 'LineWidth', 2);
    
    legend('Line Profile','Gaussian Fit','FWHM')

    % FWHM = Fibril diameter

    SA_Dia(i) = FWHM; % Store diameter values in Exf_Dia variable

end

figure;
histogram(SA_Dia)
title('Diameter distribution of self-assembled nanofibrils');
xlabel('Diameter (nm)');
ylabel('Count');
mean(SA_Dia);
std(SA_Dia);